package com.letoken.platform.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.app.service.*;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.annotation.pub.Trim;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.req.PageData;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.repo.admin.dao.AdminIssueConfigMapper;
import com.letoken.platform.repo.admin.dao.AdminSwapConfigMapper;
import com.letoken.platform.repo.admin.manager.AdminIssueConfigManager;
import com.letoken.platform.repo.admin.po.AdminIssueConfig;
import com.letoken.platform.repo.admin.po.AdminSwapConfig;
import com.letoken.platform.repo.app.dao.AppUserExchangeInfoMapper;
import com.letoken.platform.repo.app.dao.AppUserIssueMapper;
import com.letoken.platform.repo.app.dao.AppUserTeamMapper;
import com.letoken.platform.repo.app.manager.AppUserManager;
import com.letoken.platform.repo.app.po.AppUser;
import com.letoken.platform.repo.app.po.AppUserIssue;
import com.letoken.platform.repo.app.po.AppUserIssueHistory;
import com.letoken.platform.repo.app.req.config.QueryHistoryReq;
import com.letoken.platform.repo.app.req.user.AppUserMintLetReq;
import com.letoken.platform.repo.app.req.user.AppUserSwapProportionReq;
import com.letoken.platform.repo.app.req.user.AppUserSwapReq;
import com.letoken.platform.repo.app.res.config.QueryAppIssueConfigRes;
import com.letoken.platform.repo.app.res.config.QueryHistoryRes;
import com.letoken.platform.repo.app.res.config.QueryQuickSwapRes;
import com.letoken.platform.repo.app.res.config.QuerySwapConfigRes;
import com.letoken.platform.repo.app.res.team.AppBindInvitationCodeRes;
import com.letoken.platform.repo.app.res.team.QueryTeamMemberRes;
import com.letoken.platform.repo.mall.dao.AdminMallIssueConfigMapper;
import com.letoken.platform.repo.mall.dao.AppIssueCardInfoMapper;
import com.letoken.platform.repo.mall.po.AppIssueCardInfo;
import com.letoken.platform.repo.mall.po.AppMallCardInfo;
import com.letoken.platform.repo.utlis.WebUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author letokenlabs
 * @date 2022/12/3$
 */
@RestController
@RequestMapping("/quickswap")
@Api(tags = "Le账户-一键闪兑", description = "一键闪兑接口")
public class QuickSwapController {

    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private LetokenUserService letokenUserService;

    @Autowired
    private QuickSwapService quickSwapService;

    @Resource
    private AdminSwapConfigMapper adminSwapConfigMapper;

    @Resource
    private AppUserTeamMapper appUserTeamMapper;

    @Autowired
    private AppUserManager appUserManager;


    @Autowired
    private AppUserIssueHistoryService appUserIssueHistoryService;

    @Resource
    private AdminMallIssueConfigMapper adminMallIssueConfigMapper;

    @Resource
    private AppIssueCardInfoMapper appIssueCardInfoMapper;

    @Resource
    private AppUserIssueMapper appUserIssueMapper;

    @Resource
    private AdminIssueConfigMapper adminIssueConfigMapper;

    @Autowired
    private AppUserIssueService appUserIssueService;

    @Resource
    private AdminIssueConfigManager adminIssueConfigManager;

    @Resource
    AppUserExchangeInfoMapper appUserExchangeInfoMapper;



    /*@NotAuthorization
    @GetMapping("/config")
    @ApiOperation(value = "查询闪兑配置", notes = "查询闪兑配置")
    public ApiResponse<List<QuerySwapConfigRes>> queryQuickSwapConfig() {
        return ApiResponse.create(appConfigService.querySwapConfig());
    }
*/
    @PostMapping("/history")
    @ApiOperation(value = "查询闪兑记录", notes = "查询闪兑记录")
    public ApiResponse<PageData<QueryHistoryRes>> queryQuickSwapHistory(@Validated @RequestBody QueryHistoryReq req) {
        return ApiResponse.create(appConfigService.queryQuickSwapHistory(req));
    }

    @NotAuthorization
    @GetMapping("/config")
    @ApiOperation(value = "查询闪兑配置", notes = "查询闪兑配置")
    public ApiResponse<List<AdminSwapConfig>> queryQuickSwapConfig() {
        return ApiResponse.create(adminSwapConfigMapper.selectList(new QueryWrapper<AdminSwapConfig>().eq("switchs",1)));
    }


    @GetMapping("/getExchangeQuota")
    @ApiOperation(value = "查询闪兑配置", notes = "查询闪兑配置")
    public ApiResponse getExchangeQuota() {
       BigDecimal bigDecimal = appUserExchangeInfoMapper.getExchangeQuota( WebUtils.getUserId());
       if (Objects.isNull(bigDecimal) ){
           return ApiResponse.create(BigDecimal.ZERO);
       }
       return ApiResponse.create(bigDecimal.multiply(new BigDecimal(10)));
    }

    /*@GetMapping("/token_list")
    @ApiOperation(value = "查询闪兑币种", notes = "查询支持闪兑的币种（下拉框）")
    @NotAuthorization
    public ApiResponse<List<QueryQuickSwapRes>> queryQuickSwapTokenList() {
        return ApiResponse.create(appConfigService.queryQuickSwapTokenList());
    }*/

    /*@Trim
    @PostMapping("/swap")
    @ApiOperation(value = "用户闪兑", notes = "用户闪兑")
    public ApiResponse doSwap(@RequestBody @Validated AppUserSwapReq req) {
        quickSwapService.exchange(req);
        return ApiResponse.create("用户闪兑成功");
    }*/

    @Trim
    @PostMapping("/swap")
    @ApiOperation(value = "用户闪兑", notes = "用户闪兑")
    public ApiResponse doSwap(@RequestBody @Validated AppUserSwapReq req) {
        quickSwapService.exchange(req);
        return ApiResponse.create("闪兑成功");
    }

    @Trim
    @PostMapping("/swap/proportion")
    @NotAuthorization
    @ApiOperation(value = "根据顺序返回币种闪兑比例", notes = "根据顺序返回币种闪兑比例")
    public ApiResponse<String> doSwapProportion(@RequestBody @Validated AppUserSwapProportionReq req) {
        return ApiResponse.create(quickSwapService.doSwapProportion(req.getFromType(),req.getToType()));
    }


    @PostMapping("/issue")
    @ApiOperation(value = "铸币发行-发行", notes = "立即发行")
    public synchronized ApiResponse<AppBindInvitationCodeRes> tokenIssue(@RequestBody @Validated AppUserMintLetReq req) {
        quickSwapService.MintLet(req);
        return ApiResponse.create();
    }

    @PostMapping("/issueTeamValue")
    @ApiOperation(value = "团队业绩", notes = "团队业绩")
    public synchronized ApiResponse issueTeamValue() {
        AppUser user = appUserManager.queryMe();
        Integer userId = user.getId();
        return ApiResponse.create(appUserTeamMapper.issueTeamValue(userId));
    }

    @GetMapping("/getMallCardInfo")
    @ApiOperation(value = "卡劵-查看卡劵", notes = "卡劵-查看卡劵")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "state", value = "1.可使用 2.已使用 3.已过期", required = true)})
    public ApiResponse<List<AppMallCardInfo>> getMallCardInfo(@RequestParam("state") Integer state){
        Integer userId = WebUtils.getUserId();
        QueryWrapper<AppIssueCardInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("state",state);
        List<AppIssueCardInfo> infoList = appIssueCardInfoMapper.selectList(queryWrapper);
        for (AppIssueCardInfo appMallCardInfo:infoList) {
            if(appMallCardInfo.getExpiredTime().isBefore(LocalDateTime.now()) && !appMallCardInfo.getState().equals(3)){
                appMallCardInfo.setState(3);
                appMallCardInfo.updateById();
            }
        }
        infoList = infoList.stream().filter(i -> i.getState().equals(state)).collect(Collectors.toList());
        return ApiResponse.create(infoList);
    }


    @GetMapping("/useCoupons")
    @ApiOperation(value = "卡劵-使用卡劵", notes = "卡劵-使用卡劵")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "cardId", value = "卡劵id", required = true)})
    public ApiResponse<List<AppMallCardInfo>> useCoupons(@RequestParam("cardId") Integer cardId){
        AdminIssueConfig mintConfig = adminIssueConfigManager.queryLet();
        appUserIssueService.useCoupons(cardId,mintConfig);
        return ApiResponse.create();
    }

}
